<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/6/30
 * Time: 9:19
 */

namespace front\modules\vote\controllers;


use common\helpers\StringHelper;
use EasyWeChat\Foundation\Application;
use front\controllers\WebBaseController;
use GuzzleHttp\Client;
use wechat\models\VoteBrowsingRecord;
use wechat\models\VoteShare;
use wechat\services\AccountService;
use wechat\services\VoteService;
use Yii;
use yii\helpers\Json;

class VoteController extends WebBaseController
{

//    public $layout = false;

    public function actionIndex()
    {
        //获取授权
        $session = \yii::$app->session;
        if (empty($session->get('openId'))) {
            $conf = AccountService::getWechatConfig(self::ORIGINAL_ID);
            $app = new Application($conf);
            $oauth = $app->oauth;
            Yii::$app->session->set('target_url', '/vote/vote');
            $oauth->redirect()->send();
        }

        //添加浏览记录
        $brow_record = new VoteBrowsingRecord();
        $brow_record->created_at = time();
        $brow_record->openid = $session->get('openId');
        $brow_record->save();

        //准备数据
        $data = [];
        $data['enroll_count'] = VoteService::getEnrollCcount();
        $data['browsing_count'] = VoteService::getBrowsingCount();
        $data['vote_count'] = VoteService::getVoteCount();

        $data['js_conf'] = $this->getJs_ticket('http://shopbox.10000dt.com/vote/vote');




        return $this->render('index', ['data'=>$data]);
    }

    public function actionList()
    {
        //获取授权
        $session = \yii::$app->session;
        if (empty($session->get('openId'))) {
            $conf = AccountService::getWechatConfig(self::ORIGINAL_ID);
            $app = new Application($conf);
            $oauth = $app->oauth;
            Yii::$app->session->set('target_url', '/vote/vote');
            $oauth->redirect()->send();
        }

        $_GET['page'] = 1;
        $_GET['per-page'] = 4;
        $param=[
            'sort'=>0
        ];
        $data['list_order_hot'] = VoteService::getEnrollList($param);
        $param['sort'] = 1;
        $data['list_order_id'] = VoteService::getEnrollList($param);
        $data['js_conf'] = $this->getJs_ticket('http://shopbox.10000dt.com/vote/vote/list');
        $session = \yii::$app->session;
        $vote_record = VoteService::getVoteRecord(['supporter_openid' => $session->get('openId')]);
        $data['voted_id'] = 0;
        if(!empty($vote_record)){
            $data['voted_id'] = $vote_record[0]['red_net_uid'];
        }
        return $this->render('list', ['data'=>$data]);
    }

    public function actionAjaxList()
    {
        $data = [];
        $sort = \yii::$app->request->get('sort');
        $param=[
            'sort'=>$sort
        ];
        $data['list'] = VoteService::getEnrollList($param);
        $session = \yii::$app->session;
        $vote_record = VoteService::getVoteRecord(['supporter_openid' => $session->get('openId')]);
        $data['voted_id'] = 0;
        if(!empty($vote_record)){
            $data['voted_id'] = $vote_record[0]['red_net_uid'];
        }
        echo trim($_GET['funcName']).'('.Json::encode($data).')';
        exit;
    }


    public function actionSearch()
    {
        //获取授权
        $session = \yii::$app->session;
        if (empty($session->get('openId'))) {
            $conf = AccountService::getWechatConfig(self::ORIGINAL_ID);
            $app = new Application($conf);
            $oauth = $app->oauth;
            Yii::$app->session->set('target_url', '/vote/vote');
            $oauth->redirect()->send();
        }


        $data = [];
        $val = isset($_GET['val']) ? $_GET['val'] : null;
        $sort = \yii::$app->request->get('sort');
        $param=[
            'sort'=>0,
            'nick_name' => $val,
            'id' => $val
        ];
        $data['list'] = VoteService::getEnrollList($param);
        $session = \yii::$app->session;
        $vote_record = VoteService::getVoteRecord(['supporter_openid' => $session->get('openId')]);
        $data['voted_id'] = 0;
        if(!empty($vote_record)){
            $data['voted_id'] = $vote_record[0]['red_net_uid'];
        }
        $data['js_conf'] = $this->getJs_ticket('http://shopbox.10000dt.com/vote/vote/search?val=' . $val);
        return $this->render('search', ['data'=>$data]);
    }

    public function actionVote(){
        $param['red_net_uid'] = \yii::$app->request->post('id');

        $session = \yii::$app->session;
        $param['supporter_openid'] = $session->get('openId');
        if(VoteService::vote($param)){
            echo 0;//当天已经投过票
            exit;
        }
        echo 1;//投票成功
        exit;

    }

    public function actionShare(){
        $type = \yii::$app->request->post('type');
        $url = \yii::$app->request->post('url');
        $session = \yii::$app->session;
        $openId = $session->get('openId');
        $model = new VoteShare();
        $model->openid = $openId;
        $model->url = $url;
        $model->type = $type;
        $model->created_at = time();
        if($model->save()){
            echo 1;
            exit;
        }
        echo 0;
        exit;
    }


    private function getJs_ticket($url)
    {
        //准备分享参数
        if (!empty($_SESSION['ticket']) && ($_SESSION['ticket_time'] < time())){
            $jsapi_ticket = $_SESSION['ticket'];
        }else {
            //获取access_token
            if(empty($_SESSION['token']) || empty($_SESSION['expires_in']) || ($_SESSION['expires_in'] > time())) {
                $clent = new Client([
                    'base_uri' => 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb92c2bb9c487c950&secret=4531c2e3fcf9438320af5cb85b068549',
                    'timeout' => 30,
                ]);
                $response = $clent->request('get');
                $ret = Json::decode($response->getBody(), true);
                $_SESSION['token'] = $ret['access_token'];
                $_SESSION['expires_in'] = time() + 7200;
            }
            $access_token = $_SESSION['token'];

            //获取ticket
            $clent = new Client([
                'base_uri' => 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $access_token . '&type=jsapi',
                'timeout' => 30,
            ]);
            $response = $clent->request('get');
            $ret = Json::decode($response->getBody(), true);
            $jsapi_ticket = $ret['ticket'];
            $_SESSION['ticket'] = $jsapi_ticket;
            $_SESSION['ticket_time'] = time() + 7200;
        }
        //生成签名
        $time = time();
        $noncestr = StringHelper::random(16);
//        $url = 'http://shopbox.10000dt.com/vote/vote';
        $signature = 'jsapi_ticket=' . $jsapi_ticket . '&noncestr=' . $noncestr . '&timestamp=' . $time . '&url=' . $url;
        $signature = sha1($signature);

        return ['time'=>time(), 'signature' => $signature, 'noncestr' => $noncestr];
    }
}